package cn.kattomy.shop.order.action;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.kattomy.shop.cart.vo.Cart;
import cn.kattomy.shop.cart.vo.CartItem;
import cn.kattomy.shop.order.service.OrderService;
import cn.kattomy.shop.order.vo.Order;
import cn.kattomy.shop.order.vo.OrderItem;
import cn.kattomy.shop.user.vo.User;
import cn.kattomy.shop.utils.PageBean;
import cn.kattomy.shop.utils.PaymentUtil;
import sun.nio.ch.SelChImpl;

/**
 * 订单管理的 Action
 * @author kattomy
 *
 */
public class OrderAction extends ActionSupport implements ModelDriven<Order> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	//注入 OrderService
	private OrderService orderService;
	
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	//当前页面pageNo参数
	private Integer pageNo;
	
	//接收支付通道编码
	private String pd_FrpId;
	
	//接收付款成功后的响应数据
	private String r6_Order;
	private String r3_Amt;
	
	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}
	
	public void setPd_FrpId(String pd_FrpId) {
		this.pd_FrpId = pd_FrpId;
	}

	/**
	 * 提交订单的执行方法
	 * @return
	 */
	public String save() {
		//1.保存数据到数据库
		//订单数据补全
		
		order.setOrdertime(new Date());//订单创建时间
		order.setState(1);//订单状态 1:未付款	2.已付款未发货	3.已发货未确认	4.确认收货完成交易
		
		//总计是购物车中的信息：
		Cart cart = (Cart) ServletActionContext.getRequest().getSession().getAttribute("cart");
		if (cart == null) {
			this.addActionError("亲！您还没有购物！请先购物后再结算");
			return "msg";
		}
		order.setTotal(cart.getTotal());//总计(总金额)
		
		//设置订单中的订单项
		for (CartItem cartItem : cart.getCartItems()) {
			OrderItem orderItem = new OrderItem();
			orderItem.setCount(cartItem.getCount());
			orderItem.setProduct(cartItem.getProduct());
			orderItem.setSubtotal(cartItem.getSubtotal());
			orderItem.setOrder(order);
			
			order.getOrderItems().add(orderItem);
		}
		
		//设置订单所属用户
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
		
		if (user == null) {
			this.addActionMessage("请先登录！");
			return "loginPage";
		}
		order.setUser(user);
		orderService.save(order);
		
		//2.将订单对象显示到页面上：
		//通过值栈的方式:因为 Order 显示的对象就是模型驱动的使用对象
		//清空购物车
		cart.clearCart();
		
		return "saveSuccess";
	}
	
	/**
	 * 查询当前用户的执行方法
	 * @return
	 */
	public String findByUid() {
		//获取用户 (根据 uid)
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
		
		//调用 Service
		PageBean<Order> pageBean = orderService.findByUid(user.getUid(), pageNo);
		
		//将分页数据显示到页面上
		ActionContext.getContext().getValueStack().set("pageBean", pageBean);
		
		return "findByUidSuccess";
	}
	
	/**
	 * 根据订单的 id 查询订单
	 */
	public String findByOid(){
		order = orderService.findByOid(order.getOid());
		return "findByOidSuccess";
	}
	
	//模型驱动使用的对象
	private Order order = new Order();
	
	@Override
	public Order getModel() {
		
		return order;
	}
	
	//为订单付款的方法
	public String payOrder() throws IOException{
		
		//修改订单
		System.out.println(order.getOid());
		Order currOrder = orderService.findByOid(order.getOid());
		currOrder.setAddr(order.getAddr());
		currOrder.setName(order.getName());
		currOrder.setPhone(order.getPhone());
		orderService.update(currOrder);
		
		//为订单付款
		//传递 yeePay 支付参数
		String p0_Cmd = "Buy"; //业务类型
		String p1_MerId = "10001126856"; //商户编号
		String p2_Order = order.getOid().toString(); //订单编号
		String p3_Amt = "0.01"; //付款金额
		String p4_Cur = "CNY"; //交易币种
		String p5_Pid = ""; //商品名称
		String p6_Pcat = ""; //商品种类
		String p7_Pdesc = ""; //商品描述
		String p8_Url = "http://localhost:8080/shop/order_callBack.action"; //支付成功后跳转的页面路径
		String p9_SAF = ""; //送货地址
		String pa_MP = ""; //商户的扩展信息
		String pd_FrpId = this.pd_FrpId; //支付通道编码
		String pr_NeedResponse = "1"; //应答机制
		String keyValue = "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl";
		String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, 
				p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue); //
		
		//向 yeePay 出发
		StringBuffer sb = new StringBuffer("https://www.yeepay.com/app-merchant-proxy/node?");
		sb.append("p0_Cmd=").append(p0_Cmd).append("&");
		sb.append("p1_MerId=").append(p1_MerId).append("&");
		sb.append("p2_Order=").append(p2_Order).append("&");
		sb.append("p3_Amt=").append(p3_Amt).append("&");
		sb.append("p4_Cur=").append(p4_Cur).append("&");
		sb.append("p5_Pid=").append(p5_Pid).append("&");
		sb.append("p6_Pcat=").append(p6_Pcat).append("&");
		sb.append("p7_Pdesc=").append(p7_Pdesc).append("&");
		sb.append("p8_Url=").append(p8_Url).append("&");
		sb.append("p9_SAF=").append(p9_SAF).append("&");
		sb.append("pa_MP=").append(pa_MP).append("&");
		sb.append("pd_FrpId=").append(pd_FrpId).append("&");
		sb.append("pr_NeedResponse=").append(pr_NeedResponse).append("&");
		sb.append("hmac=").append(hmac);
		
		//重定向到 yeePay
		ServletActionContext.getResponse().sendRedirect(sb.toString());
		
		return NONE;
	}

	public String callBack(){
		//修改订单状态：修改状态为已付款
		Order currOrder = orderService.findByOid(Integer.parseInt(pd_FrpId));
		currOrder.setState(2);
		orderService.update(currOrder);
		//在页面显示付款成功的信息
		this.addActionMessage("订单付款成功： 订单编号：" + r6_Order + "付款金额：" + r3_Amt);
		
		return " "
				+ ". =";
	}
	
	//确认收货：修改订单状态
	public String updateState(){
		//根据订单 id 查询订单
		Order currOrder = orderService.findByOid(order.getOid());
		currOrder.setState(4);
		orderService.update(currOrder);
		return "updateStateSuccess";
	}
}
